package com.hotel.dao.impl;

import com.hotel.dao.TableDao;
import com.hotel.pojo.Table;
import com.hotel.pojo.TableStatus;
import com.hotel.utils.JdbcUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by LinYaTing on 2018/11/24 22:56
 */
public class TableDaoImpl implements TableDao {

    @Override
    public void save(Table table) {
        String sql = "insert into dinnertable(tableName, orderTime) values(?, ?)";
        try {
            JdbcUtils.getQueryRunner().update(sql, table.getTableName(), table.getOrderTime());
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    public List<Table> findAll() {
        String sql = "select * from dinnertable";
        try {
            return JdbcUtils.getQueryRunner().query(sql, new BeanListHandler<Table>(Table.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Table> findNoUseTable(TableStatus status) {
        String sql = "select * from dinnertable where tableStatus = ?";
        try {
            return JdbcUtils.getQueryRunner().query(sql, new BeanListHandler<Table>(Table.class), status.ordinal());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Table> findTableByName(String tableName) {
        String sql = "select * from dinnertable where tableName like ?";
        try {
            return JdbcUtils.getQueryRunner().query(sql, new BeanListHandler<Table>(Table.class), "%" + tableName + "%");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Table table) {
        String sql = "update dinnertable set tableStatus = ?,orderTime = ? where id =? ";
        try {
            JdbcUtils.getQueryRunner().update(sql, table.getTableStatus(), table.getOrderTime(), table.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id) {
        String sql = "delete from dinnertable where id = ?";
        try {
            JdbcUtils.getQueryRunner().update(sql, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Table findById(Integer id) {
        String sql = "select * from dinnertable where id = ?";
        try {
            return JdbcUtils.getQueryRunner().query(sql, new BeanHandler<Table>(Table.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
